﻿using System;
using System.Diagnostics;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using HandyControl;
using HandyControl.Controls;
using HandyControl.Data;
using Microsoft.Win32;
using YJTTool.Common.Events;
using MessageBox = HandyControl.Controls.MessageBox;
namespace YJTTool.Handy.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    { // 开机启动注册表路径
        private const string RunRegistryKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
        private const string AppName = "YJTTool.Handy";
        public MainWindow()
        {
            InitializeComponent();
            LoginVisibilityEvent.Instance.Subscribe(LoginCommandMethod);
            // 双击托盘图标恢复窗口
            notifyIcon.MouseDoubleClick += (s, e) =>
            {
                this.Show();
                this.WindowState = WindowState.Normal;
                notifyIcon.Visibility = Visibility.Collapsed;
            };
        }
        private bool IsStartupEnabled()
        {
            using (var key = Registry.CurrentUser.OpenSubKey(RunRegistryKey))
            {
                return key?.GetValue(AppName) != null;
            }
        }
        private void SetStartup(bool enable)
        {
            try
            {
                using (var key = Registry.CurrentUser.CreateSubKey(RunRegistryKey))
                {
                    if (enable)
                    {
                        var exePath = Process.GetCurrentProcess().MainModule.FileName;
                        key.SetValue(AppName, $"\"{exePath}\" -minimized");
                    }
                    else
                    {
                        key.DeleteValue(AppName, false);
                    }
                }
            }
            catch (SecurityException)
            {
                Growl.Warning("需要管理员权限才能修改启动项");
            }
        }
        private MenuItem GetStartupMenuItem()
        {
            if (TryFindResource("ContextMenu") is ContextMenu contextMenu)
            {
                return FindVisualChild<MenuItem>(contextMenu, "StartupMenuItem");
            }
            return null;
        }
        private T FindVisualChild<T>(DependencyObject parent, string name) where T : FrameworkElement
        {
            if (parent == null) return null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T result && result.Name == name)
                    return result;

                var childResult = FindVisualChild<T>(child, name);
                if (childResult != null)
                    return childResult;
            }
            return null;
        }
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = GetStartupMenuItem();
            if (menuItem == null) return;

            try
            {
                var enable = !menuItem.IsChecked;
                SetStartup(enable);

                menuItem.IsChecked = enable;
                menuItem.Header = enable ? "✔ 开机自启" : "开机自启";

                // 使用 HandyControl 的 Growl 显示通知
                Growl.Info($"开机自启已{(enable ? "启用" : "关闭")}");
            }
            catch (Exception ex)
            {
                Growl.Error($"操作失败: {ex.Message}");
            }
        }
        // 最小化到托盘
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
            this.Hide();
            notifyIcon.Visibility = Visibility.Visible;
        }
        // 退出软件
        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Info("确定要退出程序吗？") == MessageBoxResult.OK)
            {
                notifyIcon.Dispose();
                Application.Current.Shutdown();
            }
        }
        // 窗口状态处理
        protected override void OnStateChanged(EventArgs e)
        {
            if (WindowState == WindowState.Minimized)
            {
                this.Hide();
                notifyIcon.Visibility = Visibility.Visible;
            }
            base.OnStateChanged(e);
        }
        private void LoginCommandMethod(Visibility visibility)
        {
            if (visibility == Visibility.Collapsed)
            {
                GlobalLoadingMask.Visibility = Visibility.Collapsed;
            }
            else
            {
                GlobalLoadingMask.Visibility = Visibility.Visible;
            }
        }

    }
}
